<template>
  <div ref="chart" style="width: 100%; height: 260px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';

dayjs.extend(utc); // 扩展 dayjs 支持 utc

export default {
  name: 'MyDepartmentEChart',
  props: {
    chartData: {
      type: Array, // 接收后端返回的统计数据
      required: true
    }
  },
  data() {
    return {
      myChart: null, // 用于存储 ECharts 实例
      option: {
        title: { text: '' },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross', crossStyle: { color: '#999' } }
        },
        legend: { data: [] },
        xAxis: { type: 'category', name: '日期', data: [] },
        yAxis: { type: 'value', name: '数量' },
        series: []
      }
    };
  },
  watch: {
    chartData: {
      handler(newData) {
        if (this.myChart) this.updateChart(newData);
      },
      immediate: true
    }
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      this.myChart = echarts.init(this.$refs.chart);
      this.myChart.setOption(this.option);
    },
    getLastSevenDays() {
      const yesterday = dayjs().subtract(1, 'day'); 
      return Array.from({ length: 7 }, (_, i) => yesterday.subtract(6 - i, 'day').format('YYYY-MM-DD'));
    },
    fillMissingData(data) {
      const dateRange = this.getLastSevenDays();
      return dateRange.map((date) => {
        const existingData = data.find((item) => dayjs.utc(item.date).format('YYYY-MM-DD') === date);
        return existingData || { date, newPatients: 0, newDiagnoseds: 0, newRecords: 0 };
      });
    },
    updateChart(data) {
      if (!this.myChart || !data.length) return;

      const filledData = this.fillMissingData(data);
      const getCN = {
        newPatients: '新增患者',
        newDiagnoseds: '新增确诊',
        newRecords: '新增记录'
      };

      const seriesNames = Object.keys(filledData[0]).filter((key) => key !== 'date' && key !== 'departmentId');
      this.option.legend.data = seriesNames.map((name) => getCN[name] || name);
      this.option.xAxis.data = filledData.map((item) => dayjs.utc(item.date).format('MM-DD'));
      this.option.series = seriesNames.map((name) => ({
        name: getCN[name] || name,
        type: name === 'newRecords' ? 'line' : 'bar',
        data: filledData.map((item) => item[name] || 0)
      }));

      this.myChart.setOption(this.option);
    }
  }
};
</script>

<style scoped>
</style>